import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import * as api from '../utils/api';
import { logout } from '../utils/auth';
import { TournamentState, TournamentRound, Team, Match, TournamentConfig } from '../types';

const TournamentPage: React.FC = () => {
  const navigate = useNavigate();
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRegistering, setIsRegistering] = useState(false);
  const [showTeamForm, setShowTeamForm] = useState(false);
  const [isSettingRound, setIsSettingRound] = useState(false);
  const [teams, setTeams] = useState([
    { name: '自由与快乐', captain: '韦阳阳' },
    { name: '50度的太阳', captain: '黄家喜' },
    { name: '不停线对不队', captain: '刘佳' },
    { name: '羽众不同', captain: '江超' },
    { name: '拼搏进取', captain: '李家乐' },
    { name: '草原猛兽组合', captain: '王浩' },
    { name: '飞天击球队', captain: '齐星' },
    { name: '一路飞驰', captain: '洪亮' },
    { name: '大小姐', captain: '陈倩' },
    { name: '杀球小分队', captain: '俞为俊' }
  ]);

  useEffect(() => {
    loadTournamentStatus();
  }, []);

  const loadTournamentStatus = async () => {
    try {
      setLoading(true);
      const [statusResponse, configResponse] = await Promise.all([
        api.getTournamentStatus(),
        api.getTournamentConfig()
      ]);

      if (statusResponse.success && statusResponse.tournament_state) {
        setTournamentState(statusResponse.tournament_state);
      }

      if (configResponse.success && configResponse.config) {
        setTournamentConfig(configResponse.config);
      }

      setError(null);
    } catch (err) {
      setError('加载比赛状态失败');
      console.error('加载比赛状态失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleRegisterTeams = async () => {
    try {
      setIsRegistering(true);
      setError(null);

      const response = await api.registerTeams({ teams });
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
        setShowTeamForm(false);
      } else {
        setError(response.error || '注册队伍失败');
      }
    } catch (err) {
      setError('注册队伍失败');
      console.error('注册队伍失败:', err);
    } finally {
      setIsRegistering(false);
    }
  };



  const updateTeam = (index: number, field: 'name' | 'captain', value: string) => {
    const newTeams = [...teams];
    newTeams[index][field] = value;
    setTeams(newTeams);
  };

  const handleResetTournament = async () => {
    if (!confirm('确定要重置比赛吗？这将清除所有比赛数据！')) {
      return;
    }

    try {
      setLoading(true);
      const response = await api.resetTournament();
      if (response.success) {
        setTournamentState(null);
        setError(null);
      } else {
        setError(response.error || '重置比赛失败');
      }
    } catch (err) {
      setError('重置比赛失败');
      console.error('重置比赛失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const getRoundDisplayName = (round: TournamentRound): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round; // 如果找不到配置，返回原始名称
  };

  const getStatusDisplayName = (status: string): string => {
    const statusNames: Record<string, string> = {
      'registered': '已报名',
      'grouped': '已分组',
      'advanced': '晋级',
      'eliminated': '淘汰',
      'revived': '复活',
      'final_paired': '决赛配对',
      'champion': '冠军',
      'runner_up': '亚军'
    };
    return statusNames[status] || status;
  };

  const navigateToMatchResult = () => {
    navigate('/match-result');
  };

  const navigateToRoundManage = () => {
    navigate('/round-manage');
  };

  const navigateToTournamentControl = () => {
    navigate('/tournament-control');
  };

  const handleSetCurrentRound = async (roundName: string) => {
    try {
      setIsSettingRound(true);
      setError(null);

      const response = await api.setCurrentRound(roundName);
      if (response.success && response.tournament_state) {
        setTournamentState(response.tournament_state);
      } else {
        setError(response.error || '设置当前轮次失败');
      }
    } catch (err) {
      setError('设置当前轮次失败');
      console.error('设置当前轮次失败:', err);
    } finally {
      setIsSettingRound(false);
    }
  };



  const navigateToBracket = () => {
    navigate('/bracket');
  };

  const handleLogout = () => {
    if (confirm('确定要登出吗？')) {
      logout();
      window.location.reload(); // 刷新页面以触发认证检查
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-6xl mx-auto">
        {/* 标题 */}
        <div className="text-center mb-8 relative">
          <h1 className="text-4xl md:text-5xl font-bold text-white mb-4">
            储能工厂羽毛球大赛
          </h1>
          <p className="text-xl text-blue-200">比赛管理系统</p>

          {/* 登出按钮 */}
          <button
            onClick={handleLogout}
            className="absolute top-0 right-0 bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
          >
            登出
          </button>
        </div>

        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded-lg mb-6">
            {error}
          </div>
        )}

        {!tournamentState ? (
          // 比赛未开始
          <div className="space-y-6">
            {/* 队伍管理 */}
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold text-white">队伍管理</h2>
                <button
                  onClick={() => setShowTeamForm(!showTeamForm)}
                  className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  {showTeamForm ? '隐藏编辑' : '编辑队伍'}
                </button>
              </div>

              {showTeamForm ? (
                // 队伍编辑表单
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {teams.map((team, index) => (
                      <div key={index} className="bg-white/20 rounded-lg p-4">
                        <div className="text-white font-semibold mb-2">第{index + 1}队</div>
                        <div className="space-y-2">
                          <input
                            type="text"
                            placeholder="队伍名称"
                            value={team.name}
                            onChange={(e) => updateTeam(index, 'name', e.target.value)}
                            className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded text-white placeholder-white/60"
                          />
                          <input
                            type="text"
                            placeholder="队长姓名"
                            value={team.captain}
                            onChange={(e) => updateTeam(index, 'captain', e.target.value)}
                            className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded text-white placeholder-white/60"
                          />
                        </div>
                      </div>
                    ))}
                  </div>

                  <div className="text-center">
                    <button
                      onClick={handleRegisterTeams}
                      disabled={isRegistering}
                      className="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 text-white font-bold py-3 px-8 rounded-lg transition-colors duration-200"
                    >
                      {isRegistering ? '正在注册...' : '注册队伍'}
                    </button>
                  </div>
                </div>
              ) : (
                // 队伍展示
                <div>
                  <h3 className="text-lg font-semibold text-blue-200 mb-4">参赛队伍 (10队)</h3>
                  <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                    {teams.map((team, index) => (
                      <div key={index} className="bg-white/20 rounded-lg p-3">
                        <div className="font-semibold text-white">{team.name}</div>
                        <div className="text-sm text-blue-200">队长: {team.captain}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        ) : (
          // 比赛进行中或已结束
          <div className="space-y-6">
            {/* 比赛状态概览 */}
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
              <div className="flex justify-between items-center mb-4">
                <h2 className="text-2xl font-bold text-white">比赛状态</h2>
                <div className="text-lg font-semibold text-blue-200">
                  当前阶段: {getRoundDisplayName(tournamentState.current_round)}
                </div>
              </div>

              {/* 轮次控制 */}
              {/*<div className="mb-6">*/}
              {/*  <h4 className="text-lg font-semibold text-white mb-3">轮次控制</h4>*/}
              {/*  <div className="flex flex-wrap gap-2 mb-4">*/}
              {/*    {(tournamentConfig?.rounds || []).map((roundConfig) => (*/}
              {/*      <button*/}
              {/*        key={roundConfig.name}*/}
              {/*        onClick={() => handleSetCurrentRound(roundConfig.name)}*/}
              {/*        disabled={isSettingRound || tournamentState.current_round === roundConfig.name}*/}
              {/*        className={`py-2 px-3 rounded text-sm font-bold transition-colors duration-200 ${*/}
              {/*          tournamentState.current_round === roundConfig.name*/}
              {/*            ? 'bg-blue-600 text-white cursor-default'*/}
              {/*            : 'bg-gray-600 hover:bg-gray-700 disabled:bg-gray-500 text-white'*/}
              {/*        }`}*/}
              {/*      >*/}
              {/*        {isSettingRound ? '设置中...' : roundConfig.display_name}*/}
              {/*      </button>*/}
              {/*    ))}*/}
              {/*  </div>*/}
              {/*</div>*/}

              {/* 快捷操作按钮 */}
              <div className="flex flex-wrap gap-4 mb-6">
                <button
                  onClick={() => navigate('/draw')}
                  className="bg-yellow-600 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  队长抽签页面
                </button>
                <button
                  onClick={navigateToTournamentControl}
                  className="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  比赛控制台
                </button>
                <button
                  onClick={navigateToRoundManage}
                  className="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  轮次管理
                </button>
                <button
                  onClick={navigateToMatchResult}
                  className="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  比赛结果
                </button>
                <button
                  onClick={navigateToBracket}
                  className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  对阵图
                </button>
                <button
                  onClick={handleResetTournament}
                  className="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                >
                  重置比赛
                </button>
              </div>

              {/* 冠亚军显示 */}
              {tournamentState.current_round === 'completed' && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                  {tournamentState.champion && (
                    <div className="bg-yellow-500/20 border border-yellow-500 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-yellow-300 mb-2">🏆 冠军</div>
                      <div className="text-xl font-semibold text-white">{tournamentState.champion.name}</div>
                      <div className="text-blue-200">队长: {tournamentState.champion.captain}</div>
                    </div>
                  )}
                  {tournamentState.runner_up && (
                    <div className="bg-gray-500/20 border border-gray-500 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-gray-300 mb-2">🥈 亚军</div>
                      <div className="text-xl font-semibold text-white">{tournamentState.runner_up.name}</div>
                      <div className="text-blue-200">队长: {tournamentState.runner_up.captain}</div>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 队伍状态 */}
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
              <h3 className="text-xl font-bold text-white mb-4">队伍状态</h3>
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                {tournamentState.teams.map((team) => (
                  <div key={team.id} className="bg-white/20 rounded-lg p-3">
                    <div className="font-semibold text-white">{team.name}</div>
                    <div className="text-sm text-blue-200">队长: {team.captain}</div>
                    <div className="text-sm text-green-300">{getStatusDisplayName(team.status)}</div>
                    {team.group && (
                      <div className="text-xs text-yellow-300">分组: {team.group}</div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default TournamentPage;
